import React from 'react';
import { Cascader, Spin } from 'antd';
import { useRequest, defaultFormatResult } from '@/hooks';
import { getOrganizationTree } from '@/services/Organization/orgmanage';

const filterTree = (tree = [], arr = []) =>
    tree.map(({ children, organizationCode, ...props }) => {
        const value = arr.concat(organizationCode);
        return {
            children: children && children.length > 0 ? filterTree(children, value) : '',
            organizationCode,
            value,
            ...props
        };
    });

// 获取组件实际的value数组
const getRealValue = (treeData = [], val) => {
    let result = [];
    const filter = tree =>
        tree.forEach(({ children, value, organizationCode }) => {
            if (organizationCode === val) {
                result = value;
            }
            if (result.length === 0 && children && children.length > 0) {
                filter(children);
            }
        });
    filter(treeData);
    return result;
};

const OrganizationCascader = ({ value, onChange, params, ...props }, ref) => {
    const { data, loading } = useRequest(() => getOrganizationTree({ showTreeFlag: 1, ...params }), {
        initialData: [],
        ...defaultFormatResult
    });

    const treeData = React.useMemo(() => filterTree(data || []), [data]);

    const handleChange = (value2, selectedOptions) => {
        if (onChange) {
            onChange(value2[value2.length - 1], selectedOptions);
        }
    };

    return (
        <Spin spinning={loading}>
            <Cascader
                ref={ref}
                value={getRealValue(treeData || [], value)}
                fieldNames={{ label: 'organizationName', value: 'organizationCode' }}
                options={treeData || []}
                expandTrigger="hover"
                changeOnSelect
                showSearch
                allowClear
                {...props}
                onChange={handleChange}
            />
        </Spin>
    );
};

export default React.forwardRef(OrganizationCascader);
